using System;
using System.Linq;
using System.Linq.Expressions;

namespace System.Web.Mvc
{
	public static partial class Holovacs
	{
		public static HtmlString LabelWithSuffixFor<TModel, TProperty> (
			this HtmlHelper<TModel> htmlHelper,
			Expression<Func<TModel, TProperty>> expression,
			string suffix,
			object htmlAttributes) where TModel : class
		{
			var metaData = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
			var propertyName = metaData.PropertyName;
			var propertyDisplayName = string.IsNullOrEmpty(metaData.DisplayName) ? metaData.PropertyName : metaData.DisplayName;
			var textTip = metaData.Description ?? string.Empty;
			var name = ExpressionHelper.GetExpressionText(expression);
			var templateInfo = htmlHelper.ViewContext.ViewData.TemplateInfo;
			var fullHtmlFieldName = templateInfo.GetFullHtmlFieldName(name);
			var fullHtmlFieldId = templateInfo.GetFullHtmlFieldId(fullHtmlFieldName);
			
			var tag = new TagBuilder("label");
			tag.Attributes.Add("for", fullHtmlFieldId);
			if (!string.IsNullOrEmpty(textTip)) tag.Attributes.Add("title", textTip);
			
			if (htmlAttributes != null) {
				foreach (var kvp in htmlAttributes.GetType().GetProperties()
				 .ToDictionary(p => p.Name, p => p.GetValue(htmlAttributes, null))) {
					 tag.Attributes.Add(kvp.Key, kvp.Value.ToStringOrEmpty());
				}
			}

			tag.SetInnerText(string.Format("{0}{1}", propertyDisplayName, suffix));

			return new HtmlString(tag.ToString());
		}

		public static HtmlString LabelWithSuffixFor<TModel, TProperty> (
			this HtmlHelper<TModel> htmlHelper,
			Expression<Func<TModel, TProperty>> expression,
			string suffix) where TModel : class
		{
			return htmlHelper.LabelWithSuffixFor(expression, suffix, null);
		}

		public static HtmlString LabelWithSuffixFor<TModel, TProperty> (
			this HtmlHelper<TModel> htmlHelper,
			Expression<Func<TModel, TProperty>> expression) where TModel : class
		{
			return htmlHelper.LabelWithSuffixFor(expression, ":", null);
		}
	}
}

